document.addEventListener('DOMContentLoaded', function() {
    const messagesContainer = document.getElementById('chat-messages');
    const messageInput = document.getElementById('message-input');
    const sendButton = document.getElementById('send-button');
    const userIdInput = document.getElementById('user-id');
    const clearHistoryButton = document.getElementById('clear-history');
    
    // Function to add messages to the chat
    function addMessage(content, isUser) {
        const messageElement = document.createElement('div');
        messageElement.classList.add('message');
        messageElement.classList.add(isUser ? 'user-message' : 'bot-message');
        
        // Handle markdown-like formatting for bot responses
        if (!isUser) {
            // Convert markdown code blocks
            content = content.replace(/```(.*?)```/gs, '<pre><code>$1</code></pre>');
            // Convert markdown bold
            content = content.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
            // Convert markdown italic
            content = content.replace(/\*(.*?)\*/g, '<em>$1</em>');
            
            messageElement.innerHTML = content;
        } else {
            messageElement.textContent = content;
        }
        
        messagesContainer.appendChild(messageElement);
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }
    
    // Function to show typing indicator
    function showTypingIndicator() {
        const typingElement = document.createElement('div');
        typingElement.id = 'typing-indicator';
        typingElement.classList.add('typing-indicator');
        
        for (let i = 0; i < 3; i++) {
            const dot = document.createElement('span');
            typingElement.appendChild(dot);
        }
        
        messagesContainer.appendChild(typingElement);
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
        
        return typingElement;
    }
    
    // Function to remove typing indicator
    function removeTypingIndicator() {
        const typingElement = document.getElementById('typing-indicator');
        if (typingElement) {
            typingElement.remove();
        }
    }
    
    // Function to send message to the server
    async function sendMessage() {
        const message = messageInput.value.trim();
        const userId = userIdInput.value;
        
        if (message === '') return;
        
        // Add user message to chat
        addMessage(message, true);
        
        // Clear input field
        messageInput.value = '';
        
        // Show typing indicator
        const typingIndicator = showTypingIndicator();
        
        try {
            // Call the chat API
            const response = await fetch(`/chat?id=${userId}&message=${encodeURIComponent(message)}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            });
            
            // Remove typing indicator
            removeTypingIndicator();
            
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            
            const data = await response.text();
            
            // Add bot response to chat
            addMessage(data, false);
        } catch (error) {
            console.error('Error:', error);
            // Remove typing indicator
            removeTypingIndicator();
            addMessage('Sorry, there was an error processing your request.', false);
        }
    }
    
    // Function to save chat history to local storage
    function saveChatHistory() {
        const userId = userIdInput.value;
        const chatHistory = [];
        const messageElements = messagesContainer.querySelectorAll('.message');
        
        messageElements.forEach(element => {
            chatHistory.push({
                content: element.innerHTML,
                isUser: element.classList.contains('user-message')
            });
        });
        
        localStorage.setItem(`chatHistory_${userId}`, JSON.stringify(chatHistory));
    }
    
    // Function to load chat history from local storage
    function loadChatHistory() {
        const userId = userIdInput.value;
        const chatHistory = localStorage.getItem(`chatHistory_${userId}`);
        
        if (chatHistory) {
            // Clear current messages
            messagesContainer.innerHTML = '';
            
            const messages = JSON.parse(chatHistory);
            messages.forEach(message => {
                const messageElement = document.createElement('div');
                messageElement.classList.add('message');
                messageElement.classList.add(message.isUser ? 'user-message' : 'bot-message');
                messageElement.innerHTML = message.content;
                
                messagesContainer.appendChild(messageElement);
            });
            
            // Scroll to bottom
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }
    }
    
    // Function to clear chat history
    function clearChatHistory() {
        const userId = userIdInput.value;
        
        // Clear local storage for this user
        localStorage.removeItem(`chatHistory_${userId}`);
        
        // Reset messages container
        messagesContainer.innerHTML = '';
        
        // Add welcome message
        addMessage('你好！我是Zxt的小管家，是博客小屋的智能客服哦。我可以帮助你查询博客网站中的文章与分类，或者查找作者信息。你可以告诉我你想了解哪方面的内容吗？', false);
    }
    
    // Event listeners
    sendButton.addEventListener('click', () => {
        sendMessage().then(() => saveChatHistory());
    });
    
    messageInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendMessage().then(() => saveChatHistory());
        }
    });
    
    userIdInput.addEventListener('change', loadChatHistory);
    
    clearHistoryButton.addEventListener('click', clearChatHistory);
    
    // Load chat history on page load
    loadChatHistory();
    
    // Focus on input field when page loads
    messageInput.focus();
}); 